package com.shrio.dao.impl;

import com.shrio.dao.MemberDao;
import com.shrio.entity.Member;
import org.hibernate.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by luojie on 2018/3/14.
 */
@Repository
public class MemberDaoImpl implements MemberDao {

    @Autowired
    private SessionFactory sessionFactory;

    private Session getCurrentSession() {
        return this.sessionFactory.openSession();
    }

    @Override
    public Member get(Long id) {
        return (Member) getCurrentSession().get(Member.class,id);
    }

    @Override
    public List<Member> findAll() {
        Session session = getCurrentSession();
        Transaction tx = null;
        tx = session.beginTransaction();
        Query query =session.createQuery("from Member");
        List<Member> list = query.list();
        tx.commit();
        return list;
    }

    @Override
    public void update(Member member) {
        String hql = "update Member m set m.balance=:balance where m.id=:id";
        Query query =getCurrentSession().createQuery(hql);
        query.setParameter("balance", member.getBalance());
        query.setParameter("id", member.getId());
        query.executeUpdate();
    }

    @Override
    public Long save(Member entity) {
        return (Long)getCurrentSession().save(entity);
    }

    @Override
    public void saveOrUpdate(Member entity) {
        System.out.println(entity);
        getCurrentSession().saveOrUpdate(entity);

    }

    @Override
    public void delete(Long id) {
        Member person = get(id);
        getCurrentSession().delete(person);
    }
}
